<template>
  <div class="app-container">
    <!-- 搜索区域 -->
    <div class="search-container" >
      <el-form ref="queryFormRef" :model="queryParams" :inline="true" >
        <el-form-item label="用户标识/邀请码" prop="keywords">
          <el-input
            v-model="queryParams.keywords"
            placeholder="请输入用户标识/邀请码"
            @keyup.enter="handleQuery"
          />
        </el-form-item>

        <el-form-item label="状态" prop="status">
          <el-select
            v-model="queryParams.status"
            placeholder="全部"
            clearable
            style="width: 150px"
          >
            <el-option label="未审核" :value="1" />
            <el-option label="已通过" :value="2" />
            <el-option label="已驳回" :value="3" />

          </el-select>
        </el-form-item>



        <el-form-item label="币种" prop="currency">
          <el-select
            v-model="queryParams.currency"
            placeholder="全部"
            clearable
            style="width: 150px"
          >
            <el-option label="波场" :value="'tron'" />
            <el-option label="币安" :value="'bnb'" />
          </el-select>
        </el-form-item> 

        <el-form-item label="创建时间">
              <el-date-picker
                v-model="queryParams.createTime"
                :editable="false"
                type="daterange"
                range-separator="~"
                start-placeholder="开始时间"
                end-placeholder="截止时间"
                value-format="YYYY-MM-DD"
              />
            </el-form-item>
        

        <el-form-item class="search-buttons">
          <el-button class="filter-item" type="primary" icon="search" @click="handleQuery">
            搜索
          </el-button>
          <el-button icon="refresh" @click="handleResetQuery">重置</el-button>

          <el-button icon="info" style="margin-left: 50px;" @click="daochu_excel">导出</el-button>

           <el-button icon="info" style="margin-left: 50px;">提现总金额:{{ totalWith }}</el-button>
          <!--<el-button icon="info" style="margin-left: 50px;">实际到账总金额:0</el-button> -->

        </el-form-item>
      </el-form>
    </div>
  
    <el-card shadow="hover" class="data-table">
      <el-table
        v-loading="loading"
        :data="Lists"
        row-key="id"
        default-expand-all
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
        class="data-table__content"
        @selection-change="handleSelectionChange"
      >
        <!-- <el-table-column type="selection" width="55" align="center" /> -->

        <el-table-column prop="userId" label="用户id"  />
        
        <el-table-column prop="userInfo.account" label="用户账户">
          <template #default="{ row }">
              <div>{{ row.userInfo.account }}</div>
          </template>
        </el-table-column>


        <!-- <el-table-column prop="avatar" label="头像" width="120">
          <template #default="{ row }">
            <el-image
              style="width: 50px; height: 50px; border-radius: 50%"
              :src="row.avatar || 'https://xcx.yumeishangmao.com/uploads/8b112625e64da7e7dc69fab1044487e5.png'"
              :preview-src-list="[row.avatar]"
            />
          </template>
        </el-table-column> -->
        <!-- <el-table-column prop="order_no" label="提现订单编号"  /> -->

        <el-table-column prop="amountU" label="提现金额"  />
        <el-table-column prop="feeU" label="手续费"  />
        <el-table-column prop="actualAmountU" label="实际到账金额"  />
        <!-- <el-table-column prop="bank_name" label="开户行"  />
        <el-table-column prop="bank_address" label="开户行地址"  />
        <el-table-column prop="bank_number" label="银行卡号"  /> -->
        <el-table-column prop="currency" label="币种"  />
        <el-table-column prop="addressU" label="客户接收币地址"  />
        <el-table-column prop="remark" label="备注"  />

        <el-table-column prop="createdAt" label="创建时间" />


        <!-- <el-table-column prop="sort" label="排序" width="120" /> -->
         <el-table-column prop="examineState" label="提现状态" >
          <template #default="scope">
            <el-tag v-if="scope.row.examineState == 3" type="warning">已驳回</el-tag>
            <el-tag v-else-if="scope.row.examineState == 2" type="success">已通过</el-tag>
            <el-tag v-else type="info">未审核</el-tag>
          </template>
        </el-table-column>
        <!-- <el-table-column prop="auditTime" label="审核时间"  /> -->

        <el-table-column label="操作" fixed="right" align="left" >
          <template #default="scope">
            

            <el-button
v-if="scope.row.examineState == 1"
              v-hasPerm="['finance:withdrawal:edit']"
              type="primary"
              link
              size="small"
              icon="edit"
              @click.stop="handleOpenDialog(scope.row.id,scope.row,2)"
            >
              通过
            </el-button>

            <el-button
v-if="scope.row.examineState == 1"
              v-hasPerm="['finance:withdrawal:edit']"
              type="primary"
              link
              size="small"
              icon="edit"
              @click.stop="handleOpenDialog(scope.row.id,scope.row,3)"
            >
              驳回
            </el-button>
            
          </template>
        </el-table-column>
      </el-table>

      <pagination
            v-if="total > 0"
            v-model:total="total"
            v-model:page="queryParams.pageNum"
            v-model:limit="queryParams.pageSize"
            @pagination="handleQuery"
          />
    </el-card>

    <el-dialog
      v-model="dialog.visible"
      :title="dialog.title"
      width="600px"
      @closed="handleCloseDialog"
    >
      <el-form ref="FormRef" :model="formData" :rules="rules" label-width="120px">
        
        <el-form-item label="状态" style="display: none;">
          <el-radio-group v-model="formData.approveState">
            <el-radio :value="1">未审核</el-radio>
            <el-radio :value="2">通过</el-radio>
            <el-radio :value="3">驳回</el-radio>

          </el-radio-group>
        </el-form-item>

        <block v-show="formData.approveState==3">
            <el-form-item label="驳回原因" >
              <el-input v-model="formData.remark" placeholder="请输入驳回原因" />
            </el-form-item>
        </block>
        


      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleSubmit">确 定</el-button>
          <el-button @click="handleCloseDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
defineOptions({
  name: "提现",
  inheritAttrs: false,
});

import FinanceAPI, { WithdrawalVO, WithdrawalForm } from "@/api/system/finance.api";

const queryFormRef = ref();
const FormRef = ref();

const loading = ref(false);
const selectIds = ref<number[]>([]);

const queryParams = reactive<any>({
  pageNum: 1,
  pageSize: 10,
  keywords:'',
  status:'',
  createTime:[],
  currency:''
});
const total = ref(0);
const totalWith = ref(0);

const dialog = reactive({
  title: "",
  visible: false,
});

const Lists = ref<WithdrawalVO[]>();
const formData = reactive<WithdrawalForm>({
  id: '',
  approveState: 1,
  remark: "",
});

const rules = reactive({
  status: [{ required: true, message: "请选择状态", trigger: "change" }],
});

// 查询
function handleQuery() {
  console.log(queryParams)
  loading.value = true;

  if(queryParams.status==undefined || queryParams.status == null|| queryParams.status == 'undefined'){
    queryParams.status = ''
  }
  if(queryParams.currency==undefined || queryParams.currency == null|| queryParams.currency == 'undefined'){
    queryParams.currency = ''
  }


  FinanceAPI.getList(queryParams)
    .then((res) => {
      Lists.value = res.data;
      total.value = res.total;
      totalWith.value = res.totalWith || 0;
    })
    .catch((error) => {
      console.error("查询失败:", error);
    })
    .finally(() => {
      loading.value = false;
    });
}

// 导出
function daochu_excel() {
  console.log(queryParams)
  FinanceAPI.export_excel(queryParams).then((res) => {
    // 确保字符串以UTF-8 BOM开头，解决Excel中文乱码问题
    const BOM = '\uFEFF';
    const content = BOM + res;
    
    // 创建Blob对象
    const blob = new Blob([content], { type: 'text/csv;charset=utf-8;' });
    
    // 创建下载链接
    const link = document.createElement('a');
    const url = URL.createObjectURL(blob);
    const filename = `提现记录_${new Date().toISOString().slice(0, 10)}`;

    link.href = url;
    link.download = `${filename}.csv`;
    link.style.visibility = 'hidden';
    
    // 触发下载
    document.body.appendChild(link);
    link.click();
    
    // 清理
    document.body.removeChild(link);
    URL.revokeObjectURL(url);


  }).catch((error) => {
    console.error("导出失败:", error);
  });
}

// 重置查询
function handleResetQuery() {
  queryFormRef.value.resetFields();
  handleQuery();
}

// 处理选中项变化
function handleSelectionChange(selection: any) {
  selectIds.value = selection.map((item: any) => item.id);
}

const dialog_status = ref<number>(1);


/**
 * 打开新增弹窗
 *
 * @param Id ID
 */
async function handleOpenDialog(Id?:string,data?:WithdrawalVO,approveState?: number) {

  dialog.visible = true;
  if (Id) {
    dialog.title = "修改";
    dialog_status.value = approveState || 1;
    if(data&&approveState){
      data.approveState = approveState || 1;
      data.id = Id
    }
    Object.assign(formData, data);
  } else {
    dialog.title = "新增";
    dialog_status.value = approveState || 1;
  }
}

// 提交表单
function handleSubmit() {
  FormRef.value.validate((valid: any) => {
    if (valid) {
      loading.value = true;
      
      const formJson = {
        dataId: formData.id,
        approveState: formData?.approveState || 1,
        remark: formData?.remark || "",
      };

      //ElMessage.success("修改成功");
      FinanceAPI.edit(formJson)
        .then(() => {
          ElMessage.success("修改成功");
          handleCloseDialog();
          handleQuery();
        })
        .finally(() => (loading.value = false));
      
      // handleCloseDialog();
      // handleQuery();
      // loading.value = false
    }
  });
}



// 重置表单
function resetForm() {
  FormRef.value.resetFields();
  FormRef.value.clearValidate();
}

// 关闭弹窗
function handleCloseDialog() {
  dialog.visible = false;
  resetForm();
}

onMounted(() => {
  handleQuery();
});
</script>
<style>
.el-dialog__footer{
  border-top: 0px !important;
}
</style>
